<!-- 点歌设置 -->
<template>
  <sub-page>
    <div class="card">
      <card-top-info title="点歌设置"></card-top-info>
      <div class="songChooseForm">
        <div class="songItem">
          <div class="leftCt">
            <div class="name">是否开启点歌：</div>
            <div class="resultVal">{{ isChooseSongFuncText }}</div>
          </div>
          <div class="rightCt">
            <el-switch v-model="isChooseSongFuncOn" active-value="1" inactive-value="0"> </el-switch>
          </div>
        </div>
        <!-- 点歌模式 -->
        <div class="songItem">
          <div class="leftCt">
            <div class="name">点歌模式：</div>
            <div class="resultVal">{{ musicModeText }}</div>
          </div>
          <div class="rightCt">
            <el-switch v-model="musicMode" active-value="1" inactive-value="0"> </el-switch>
          </div>
        </div>
        <div class="songItem">
          <div class="leftCt">
            <div class="name">点歌时间段：</div>
            <div class="resultVal">{{ timeRankStr }}</div>
          </div>
          <div class="rightCt">
            <el-time-picker is-range v-model="timeRank" range-separator="至" start-placeholder="开始时间"
              end-placeholder="结束时间" placeholder="选择时间范围">
            </el-time-picker>
          </div>
        </div>
        <div class="songItem">
          <div class="leftCt">
            <div class="name">艺人分成比例：</div>
            <div class="resultVal">{{ sharePropertion }}%</div>
          </div>
          <div class="rightCt">
            <el-input-number v-model="sharePropertion" :min="0" :max="100" label="描述文字"></el-input-number>
            <label>%</label>
          </div>
        </div>
        <el-button type="primary" @click="handleConfirm" style="width: 120px; margin-left: 22%; margin-bottom: 20px">确
          定</el-button>
      </div>
      <el-dialog title="添加歌曲" :visible.sync="addDialogShow" width="400px">
        <div class="block">
          <span class="label" style="text-align: right">歌曲名称</span>
          <el-input style="width: 200px" v-model="songNameAdd" maxlength="20"></el-input>
        </div>
        <div class="block">
          <span class="label" style="text-align: right">歌曲价格</span>
          <el-input style="width: 200px" v-model="songPriceAdd"></el-input>
        </div>
        <div class="block">
          <span class="label" style="text-align: right">所属歌手</span>
          <el-select style="width: 200px" v-model="singerIdAdd" clearable placeholder="请选择 (非必填)">
            <el-option v-for="singer in singerList" :key="singer.awardid" :label="singer.name" :value="singer.awardid">
            </el-option>
          </el-select>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogShow = false">取 消</el-button>
          <el-button type="primary" @click="addSong" v-loading="isLoading">确 定</el-button>
        </span>
      </el-dialog>
      <el-dialog title="编辑歌曲" :visible.sync="editDialogShow" width="400px">
        <div class="block">
          <span class="label" style="text-align: right">歌曲名称</span>
          <el-input style="width: 200px" v-model="songNameEdit"></el-input>
        </div>
        <div class="block">
          <span class="label" style="text-align: right">歌曲价格</span>
          <el-input style="width: 200px" v-model="songPriceEdit"></el-input>
        </div>
        <div class="block">
          <span class="label" style="text-align: right">所属歌手</span>
          <el-select style="width: 200px" v-model="singerIdEdit" clearable placeholder="请选择 (非必填)">
            <el-option v-for="singer in singerList" :key="singer.awardid" :label="singer.name" :value="singer.awardid">
            </el-option>
          </el-select>
        </div>
        <div class="block">
          <span class="label" style="text-align: right">是否启用</span>
          <el-switch v-model="songStatusEdit" active-value="1" inactive-value="0"> </el-switch>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogShow = false">取 消</el-button>
          <el-button type="primary" @click="editSong">确 定</el-button>
        </span>
      </el-dialog>
      <el-dialog title="一键删除" :visible.sync="deleteDialogShow" width="400px">
        <div class="delete-dialog">
          <div class="delete-row">
            <span class="label">所属歌手</span>
            <el-select class="delete-select" v-model="deleteSingerId" clearable placeholder="不选择则删除全部歌曲">
              <el-option v-for="singer in singerList" :key="singer.awardid" :label="singer.name"
                :value="singer.awardid">
              </el-option>
            </el-select>
          </div>
          <div class="delete-tips">若选择歌手，将仅删除该歌手的歌曲。</div>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="deleteDialogShow = false">取 消</el-button>
          <el-button type="danger" @click="confirmDeleteSongs">删 除</el-button>
        </span>
      </el-dialog>
    </div>
    <div class="card">
      <card-top-info title="歌单设置"></card-top-info>
      <div class="songChooseForm">
        <div class="songItem">
          <div class="leftCt">
            <div class="name">歌单：</div>
          </div>
          <div class="rightCt">
            <el-button size="small" type="primary" @click="showAddSong">添加歌曲</el-button>
            <el-button size="small" type="primary" icon="el-icon-upload" @click="showImportDialog">批量导入歌单</el-button>
            <el-button size="small" type="danger" @click="handleDeleteAllSongs">一键删除</el-button>
          </div>
        </div>
        <el-table :data="songSheet" border style="width: 90%; margin-bottom: 20px; margin-left: 20px">
          <el-table-column prop="songName" label="歌曲名称"></el-table-column>
          <el-table-column prop="singerName" label="所属歌手" width="120"></el-table-column>
          <el-table-column prop="songPrice" label="歌曲单价" width="120"></el-table-column>
          <el-table-column prop="songPlayNum" label="被点次数" width="120"></el-table-column>
          <el-table-column label="添加时间" width="180">
            <template slot-scope="scope">
              {{ new Date(scope.row.createTime) | formatDate }}
            </template>
          </el-table-column>
          <el-table-column prop="isInUse" label="是否启用" width="120">
            <template slot-scope="scope">
              {{ scope.row.isInUse === '1' ? '启用' : '未启用' }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120">
            <template slot-scope="scope">
              <div class="link-wrap">
                <el-link type="primary" @click="deleteSong(scope.row)" style="margin-right: 20px">删除</el-link>
                <el-link type="primary" @click="showEditSong(scope.row)">修改</el-link>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination-container">
          <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page="currentPage" :page-sizes="[15, 25, 50, 100]" :page-size="currentPageSize"
            layout="total, sizes, prev, pager, next, jumper" :total="totals">
          </el-pagination>
        </div>
      </div>
    </div>
    <!-- 批量导入歌单弹窗 -->
    <my-dialog :show="isShowImportDialog">
      <div class="import-dialog-container">
        <div class="import-title" slot="title">
          <img src="@/assets/image/importList.png" alt="" width="34" height="29" />
          <div class="text">导入歌单</div>
        </div>
        <div class="import-info">
          <div class="upload-temp">
            <div class="title">
              下载导入模板
              <span>(下载后请勿更改模板格式)</span>
            </div>
            <div class="btn">
              <el-button icon="el-icon-download" type="warning" @click="downloadTemplate"> 下载 </el-button>
            </div>
          </div>
          <div class="upload-file">
            <div class="title">
              上传歌单文件
              <span>(提示：重新导入模板后将覆盖原有数据)</span>
            </div>
            <div class="block" style="padding-left: 0">
              <span class="label" style="text-align: right; width: auto">所属歌手</span>
              <el-select style="width: 200px" v-model="singerIdImport" clearable placeholder="请选择 (非必填)">
                <el-option v-for="singer in singerList" :key="singer.awardid" :label="singer.name"
                  :value="singer.awardid">
                </el-option>
              </el-select>
            </div>
            <div class="btn" style="margin-top: 10px">
              <el-upload name="uploadFile" :show-file-list="false" :http-request="handleFile" action
                accept=".xls,.xlsx">
                <el-button type="primary" icon="el-icon-upload2"> 上传 </el-button>
              </el-upload>
            </div>
          </div>
          <div class="btn-group">
            <el-button type="primary" @click="confirmUpload"> 确认导入 </el-button>
            <el-button type="info" @click="cancelUpload" style="margin-left: 20px"> 取消 </el-button>
          </div>
        </div>
      </div>
    </my-dialog>
  </sub-page>
</template>
<script>
import SubPage from '@/components/subPage';
import CardTopInfo from '@/components/cardTopInfo';
import myDialog from '@/components/myDialog'; // 新增
import { formatDate } from '@/utils/format';
import { isNumber } from '@/utils/index';
import { saveSong, editSong, getSongList, deleteAllMusic } from '@/api/setting/setting'; // 新增 deleteAllMusic
import { getActivityMsg, neidingLotteryList } from '@/api/setting/activitySetting/gameSetting';
import { editActivityMsg } from '@/api/setting/activitySetting/activity';
import request from '@/utils/request'; // 新增

export default {
  name: 'songChoose',
  components: {
    SubPage,
    CardTopInfo,
    myDialog, // 新增
  },
  data() {
    return {
      sharePropertion: 0,
      isChooseSongFuncOn: '0',
      timeRank: [new Date(2099, 1, 1, 0, 0), new Date(2099, 1, 1, 0, 0)],
      songSheet: [],
      addDialogShow: false,
      editDialogShow: false,
      songNameAdd: '',
      songPriceAdd: '',
      songNameEdit: '',
      songPriceEdit: '',
      songStatusEdit: '',
      songIdEdit: '',
      currentPage: 1,
      currentPageSize: 15,
      totals: 1,
      isLoading: false,
      musicMode: '0', // 点歌模式 1 歌手模式 0 普通模式
      singerList: [], // 歌手列表
      singerIdAdd: '', // 新增歌曲时选择的歌手ID
      singerIdEdit: '', // 编辑歌曲时选择的歌手ID
      // 批量导入相关
      isShowImportDialog: false,
      tmpFile: null,
      singerIdImport: '',
      // 一键删除
      deleteDialogShow: false,
      deleteSingerId: '',
    };
  },
  computed: {
    timeRankStr() {
      if (!this.timeRank) {
        return '';
      }
      const tempBeginDate = this.timeRank[0];
      const tempEndDate = this.timeRank[1];
      const beginDateStr = formatDate(tempBeginDate, 'hh:mm:ss');
      const endDateStr = formatDate(tempEndDate, 'hh:mm:ss');
      return `${beginDateStr}~${endDateStr}`;
    },
    isChooseSongFuncText() {
      return this.isChooseSongFuncOn === '1' ? '点歌已开启' : '点歌已关闭';
    },
    musicModeText() {
      return this.musicMode === '1' ? '歌手模式' : '普通模式';
    },
  },
  watch: {},
  created() {
    this.initBaseInfo();
    this.getSingerList().then(() => {
      this.initSongList();
    });
  },
  methods: {
    // 获取歌手列表
    getSingerList() {
      return new Promise((resolve, reject) => {
        neidingLotteryList({
          splid: this.$store.state.liveId,
          gametype: '3', // 对应歌手设置的类型
          removed: '0',
          currentPage: '1',
          showCount: '500',
        }).then((res) => {
          this.singerList = res.data.list || [];
          resolve();
        }).catch((err) => {
          console.error('获取歌手列表失败:', err);
          reject(err);
        });
      });
    },
    deleteSong(deleteData) {
      editSong({
        id: deleteData.id,
        splid: this.$store.state.liveId,
        removed: '0',
      })
        .then((res) => {
          console.log(res);
          this.$message({
            message: '删除成功!',
            type: 'success',
          });
          this.initSongList();
        })
        .catch((err) => {
          console.log(err);
          this.$message.error('删除失败!');
        });
    },
    showEditSong(editData) {
      console.log(editData);
      this.songIdEdit = editData.id;
      this.songNameEdit = editData.songName;
      this.songPriceEdit = editData.songPrice;
      this.songStatusEdit = editData.isInUse;
      this.singerIdEdit = Number(editData.singerId);
      this.editDialogShow = true;
    },
    showAddSong() {
      this.addDialogShow = true;
    },
    addSong() {
      if (!this.songNameAdd) {
        this.$message.error('歌曲名称不能为空!');
        return;
      }
      if (!this.songPriceAdd) {
        this.$message.error('歌曲价格不能为空!');
        return;
      }
      if (!isNumber(this.songPriceAdd)) {
        this.$message.error('歌曲价格非法!');
        return;
      }
      this.isLoading = true;
      saveSong({
        title: this.songNameAdd,
        money: this.songPriceAdd,
        splid: this.$store.state.liveId,
        type: 'MiaoMusic',
        singerId: this.singerIdAdd, // 传入歌手ID
      })
        .then((res) => {
          console.log(res);
          this.songNameAdd = '';
          this.songPriceAdd = '';
          this.singerIdAdd = ''; // 清空歌手ID
          this.addDialogShow = false;
          this.isLoading = false;
          this.$message({
            message: '添加成功!',
            type: 'success',
          });
          this.initSongList();
        })
        .catch((err) => {
          console.log(err);
          this.isLoading = false;
          this.$message.error('添加失败!');
        });
    },
    editSong() {
      if (!this.songNameEdit) {
        this.$message.error('歌曲名称不能为空!');
        return;
      }
      if (!this.songPriceEdit) {
        this.$message.error('歌曲价格不能为空!');
        return;
      }
      if (!isNumber(this.songPriceEdit)) {
        this.$message.error('歌曲价格非法!');
        return;
      }
      this.isLoading = true;
      editSong({
        id: this.songIdEdit,
        money: this.songPriceEdit,
        splid: this.$store.state.liveId,
        status: this.songStatusEdit,
        title: this.songNameEdit,
        singerId: this.singerIdEdit, // 传入歌手ID
      })
        .then((res) => {
          console.log(res);
          this.songIdEdit = '';
          this.songNameEdit = '';
          this.songPriceEdit = '';
          this.songStatusEdit = '';
          this.singerIdEdit = ''; // 清空歌手ID
          this.editDialogShow = false;
          this.isLoading = false;
          this.$message({
            message: '编辑成功!',
            type: 'success',
          });
          this.initSongList();
        })
        .catch((err) => {
          console.log(err);
          this.isLoading = false;
          this.$message.error('编辑失败!');
        });
    },
    handleConfirm() {
      editActivityMsg({
        is_open_music: this.isChooseSongFuncOn,
        music_rate: this.sharePropertion,
        music_start: this.timeRankStr.split('~')[0],
        music_end: this.timeRankStr.split('~')[1],
        music_mode: this.musicMode,
        splid: this.$store.state.liveId,
      })
        .then((res) => {
          console.log(res);
          this.$message({
            message: '编辑成功!',
            type: 'success',
          });
          this.initBaseInfo();
        })
        .catch((err) => {
          console.log(err);
          this.$message.error('编辑失败!');
        });
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.initSongList();
    },
    handleSizeChange(val) {
      this.currentPageSize = val;
      this.initSongList();
    },
    initSongList() {
      getSongList({
        currentPage: this.currentPage,
        showCount: this.currentPageSize,
        splid: this.$store.state.liveId,
        type: 'MiaoMusic',
        removed: '1',
      })
        .then((res) => {
          console.log(res);
          this.totals = res.data.totalResult;
          this.songSheet = res.data.list.map((item) => {
            // 根据 singerId 查找对应的歌手名称
            const singer = this.singerList.find((s) => String(s.awardid) === String(item.singerId));
            return {
              songName: item.title,
              songPrice: item.money,
              songPlayNum: item.times,
              isInUse: item.status,
              createTime: item.create_time,
              id: item.id,
              singerId: item.singerId,
              singerName: singer ? singer.name : '无', // 添加歌手名称
            };
          });
        })
        .catch((err) => {
          console.log(err);
        });
    },
    initBaseInfo() {
      getActivityMsg({
        id: this.$store.state.liveId,
      })
        .then((res) => {
          console.log(res);
          this.isChooseSongFuncOn = res.data.is_open_music;
          this.sharePropertion = res.data.music_rate;
          this.musicMode = res.data.music_mode || '0';
          this.timeRank = [
            new Date(2099, 1, 1, res.data.music_start.split(':')[0], res.data.music_start.split(':')[1]),
            new Date(2099, 1, 1, res.data.music_end.split(':')[0], res.data.music_end.split(':')[1]),
          ];
        })
        .catch((err) => {
          console.log(err);
        });
    },
    handleDeleteAllSongs() {
      this.deleteSingerId = '';
      this.deleteDialogShow = true;
    },
    confirmDeleteSongs() {
      const isSingerSelected = Boolean(this.deleteSingerId);
      const tipMessage = isSingerSelected
        ? '此操作将删除所选歌手的全部歌曲, 是否继续?'
        : '此操作将永久删除所有歌曲, 是否继续?';
      this.$confirm(tipMessage, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        deleteAllMusic({
          splid: this.$store.state.liveId,
          singerId: this.deleteSingerId,
        })
          .then(() => {
            this.$message({
              type: 'success',
              message: '删除成功!',
            });
            this.deleteDialogShow = false;
            this.initSongList();
          })
          .catch((err) => {
            console.log(err);
            this.$message.error('删除失败!');
          });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除',
        });
      });
    },
    showImportDialog() {
      this.isShowImportDialog = true;
    },
    downloadTemplate() {
      window.location.href = 'https://bar.009bar.com/reportFormsHm/findReportInfo?report_type=list_music';
    },
    handleFile(e) {
      this.tmpFile = e.file;
      this.uploadNameSheet();
    },
    uploadNameSheet() {
      if (!this.tmpFile) {
        this.$message.error('请先选择文件!');
        return;
      }
      const formData = new FormData();
      formData.append('file', this.tmpFile);
      formData.append('splid', this.$store.state.liveId);
      if (this.singerIdImport) {
        formData.append('singerId', this.singerIdImport);
      }
      request
        .post('/music/saveMusicFile', formData)
        .then(() => {
          this.$message({
            message: '上传成功!',
            type: 'success',
          });
        })
        .catch(() => {
          this.$message.error('上传失败,请检查文件格式或内容!');
        });
    },
    confirmUpload() {
      this.isShowImportDialog = false;
      this.tmpFile = null;
      this.singerIdImport = '';
      this.initSongList();
    },
    cancelUpload() {
      this.isShowImportDialog = false;
      this.tmpFile = null;
      this.singerIdImport = '';
    },
  },
  filters: {
    // 时间戳
    formatDate(time) {
      return formatDate(time, 'yyyy/MM/dd hh:mm:ss');
    },
  },
};
</script>
<style lang="less" scoped>
.card {
  display: flex;
  flex-direction: column;
  width: calc(100% - 45px);
  margin: auto;
  margin-top: 18px;
  margin-bottom: 10px;

  .songChooseForm {
    width: 100%;

    .songItem {
      width: 90%;
      display: flex;
      justify-content: space-between;
      padding: 0 20px;
      padding-bottom: 20px;

      .leftCt {
        display: flex;
        align-items: center;

        .name {
          font-size: 16px;
          width: 120px;
          margin-right: 10px;
          color: #000;
        }

        .resultVal {
          color: #999999;
          font-size: 16px;
        }
      }

      .rightCt {
        display: flex;
        align-items: center;

        label {
          color: #000;
          font-size: 18px;
          margin-left: 12px;
        }
      }
    }
  }

  .block {
    padding: 0 20px;
    display: flex;
    align-items: center;
    margin-bottom: 20px;

    .label {
      font-size: 15px;
      width: 72px;
      margin-right: 10px;

      &::after {
        content: ':';
        margin-left: 5px;
      }
    }

    .submitBtn {
      margin-left: 120px;
    }

    .tips {
      font-size: 14px;
      color: #909399;
      margin-left: 12px;
    }
  }

  .pagination-container {
    padding: 20px;
  }

  &:nth-child(2) {
    flex: 1;
  }
}

/* 导入歌单弹出框 */
.import-dialog-container {
  padding-bottom: 30px;

  .import-title {
    display: flex;
    align-items: center;

    .text {
      margin-left: 20px;
      font-size: 25px;
      font-family: SourceHanSansSC-Regular, SourceHanSansSC;
      font-weight: 400;
      color: #42474e;
    }
  }

  .import-info {
    position: relative;
    margin-left: 55px;

    &>div {
      .title {
        font-size: 14px;
        line-height: 50px;
        font-family: SourceHanSansSC-Medium, SourceHanSansSC;
        font-weight: 600;
        color: #333333;

        span {
          margin-left: 10px;
          color: #999;
          font-weight: 400;
        }
      }
    }

    .upload-temp {
      position: relative;
      margin-top: 20px;
    }

    .upload-file {
      position: relative;
      margin-top: 35px;
    }

    .btn-group {
      margin-top: 50px;
    }
  }
}

.delete-dialog {
  padding: 10px 0 20px;
  .delete-row {
    display: flex;
    align-items: center;
    .label {
      width: 72px;
      margin-right: 10px;
      font-size: 15px;
      color: #333;
      text-align: right;
      &::after {
        content: ':';
        margin-left: 5px;
      }
    }
    .delete-select {
      flex: 1;
    }
  }
  .delete-tips {
    margin-top: 12px;
    font-size: 12px;
    color: #909399;
  }
}
</style>
